﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using Crank.Core.Extensions;

namespace Crank.Core
{
    public class WhitespaceCompressingLineProvider : ILineProvider
    {
        private ILineProvider source;
        private string CurrentLine;

        public WhitespaceCompressingLineProvider(ILineProvider source)
        {
            this.source = source;
            CurrentLine = String.Empty;
        }

        private string ProcessLine(string p)
        {
            if (p == null)
                return null;
            return Regex.Replace(p, @"\s+", " ");
        }

        #region ILineProvider Members

        public bool HasLines
        {
            get
            {
                return source.HasLines;
            }
        }

        public string GetNextLine()
        {
            if (!source.HasLines)
                return null;
            CurrentLine = ProcessLine(source.GetNextLine());
            while (CurrentLine != null && CurrentLine.IsOnlyWhitespace())
                CurrentLine = ProcessLine(source.GetNextLine());
            return CurrentLine;
        }

        #endregion
    }
}
